package com.skynet.supervision.aop.validate;

import com.skynet.supervision.utils.Strings;
import lombok.val;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Objects;

public class StringInRangeValidator implements ConstraintValidator<StringInRange, String> {

    private StringInRange anno;

    @Override
    public void initialize(StringInRange constraintAnnotation) {
        anno = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        Objects.requireNonNull(anno);
        val omitEmpty = anno.omitEmpty();
        if (Strings.isEmpty(value)) {
            return omitEmpty;
        }
        val rangeConstraint = anno.value();
        return Arrays.stream(rangeConstraint)
                .anyMatch(it -> Strings.strcmp(value, it));
    }
}
